/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package actions

import (
	"gitee.com/tugoer/orivil/mux"
	"gitee.com/tugoer/wechat-share/code/model"
	"gitee.com/tugoer/orivil/bundles/admin"
)

var WeChat = []*mux.Action{
	{
		Name:"Get WeChat Configs",
		Method: "GET",
		Route: "wechat-config",
		Handler: func(ctx *mux.Context) {
			admin := admin.GetAdminFromSession(ctx)
			if admin != nil {
				ws := model.QueryWeChat(admin.ID)
				ctx.SendJson(map[string]interface{}{"list": ws})
			} else {
				ctx.MsgWarning("未登陆管理员", "")
			}
		},
	},
	{
		Name:"Create WeChat Config",
		Method: "POST",
		Route: "wechat-config",
		Params:mux.Parameters{
			{
				In:mux.Form,
				Schema: &model.WeChat{},
			},
		},
		Handler: func(ctx *mux.Context) {
			admin := admin.GetAdminFromSession(ctx)
			if admin != nil {
				w := &model.WeChat{}
				ctx.WarnParse(w)
				err := w.Create(admin.ID)
				ctx.ErrWarning(err)
				ctx.SendJson(map[string]int{
					"ID": w.ID,
				})
			} else {
				ctx.MsgWarning("未登陆管理员", "")
			}
		},
	},
	{
		Name:"Create WeChat MP.txt",
		Method: "POST",
		Route: "wechat-mp-txt",
		Params:mux.Parameters{
			{
				In:mux.Form,
				Schema: &createWeChatTxt{},
			},
		},
		Handler: func(ctx *mux.Context) {
			admin := admin.GetAdminFromSession(ctx)
			if admin != nil {
				p := &createWeChatTxt{}
				ctx.WarnParse(p)
				txtContent = p.Content
				ctx.MsgSuccess("设置成功", "")
			} else {
				ctx.MsgWarning("未登陆管理员", "")
			}
		},
	},
	{
		Name: "MP",
		Method: "GET",
		Route: "/::file",
		Handler: func(ctx *mux.Context) {
			domain, err := model.GetDomainByHost(ctx.Request.Host)
			if err != nil {
				ctx.ErrWarning(err)
			} else {
				wechat := model.GetWeChatByID(domain.WeChatID)
				ctx.WriteString(wechat.MPText)
			}
		},
	},
	{
		Name:"Update WeChat Config",
		Method: "PUT",
		Route: "wechat-config",
		Params:mux.Parameters{
			{
				In:mux.Form,
				Schema: &model.WeChat{},
			},
		},
		Handler: func(ctx *mux.Context) {
			admin := admin.GetAdminFromSession(ctx)
			if admin != nil {
				w := &model.WeChat{}
				ctx.WarnParse(w)
				err := w.Update(admin.ID)
				ctx.ErrWarning(err)
				ctx.MsgSuccess("修改成功", "")
			} else {
				ctx.MsgWarning("未登陆管理员", "")
			}
		},
	},
	{
		Name:"Delete WeChat Config",
		Method: "DELETE",
		Route: "wechat-config",
		Params:mux.Parameters{
			{
				In:mux.Query,
				Schema: &delWeChat{},
			},
		},
		Handler: func(ctx *mux.Context) {
			admin := admin.GetAdminFromSession(ctx)
			if admin != nil {
				p := &delWeChat{}
				ctx.WarnParse(p)
				w := &model.WeChat{ID: p.ID}
				err := w.Delete(admin.ID)
				ctx.ErrWarning(err)
				ctx.MsgSuccess("删除成功", "")
			} else {
				ctx.MsgWarning("未登陆管理员", "")
			}
		},
	},
}

var txtContent string

type createWeChatTxt struct {
	Content string `required:"content 不能为空"`
}

type delWeChat struct {
	ID int `required:"ID 不能为空"`
}